<?php

namespace App\Console\Commands\Cashbook;

use App\Library\Rms\RmsShopApi;
use App\Models\Cashbook\CashbookBillSyncSwitchModel;
use App\Models\Cashbook\CashbookModel;
use App\Remote\Orm\OrmNewOrderRemote;
use Illuminate\Console\Command;

class CycleBillSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cashbook:cycle_bill_sync {date?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '记账本账单同步自动同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $yesterday = $this->argument('date');
        if (!$yesterday) {
            $yesterday = date('Y-m-d', strtotime("-1 day")); //昨天时间
        }
        $time      = time();
        CashbookBillSyncSwitchModel::query()
            ->where('switch', CashbookBillSyncSwitchModel::SWITCH_ON)
            ->chunk(
                100, function ($cashbookBillSyncSwitchModel) use ($yesterday, $time) {
                $batchData = [];
                foreach ($cashbookBillSyncSwitchModel as $v) {
                    switch ($v->type) {
                        case CashbookBillSyncSwitchModel::TYPE_POS:  //自动同步每日营业额
                            $cashbookModel = CashbookModel::getInfoByRecordTime($v->shopId, strtotime($yesterday), CashbookModel::CATEGORY_1, CashbookModel::SOURCE_SYSTEM_ADD);
                            $amount        = (new RmsShopApi())->originalPrice($v->shopId, strtotime($yesterday), strtotime($yesterday) + 86399)['data']['realPayPrice'] ?? 0;//取店铺营业额数据

                            if (!$cashbookModel) {
                                $batchData[] =
                                    [
                                        'shopId'     => $v->shopId,
                                        'userId'     => 0,
                                        'recordTime' => strtotime($yesterday),
                                        'type'       => CashbookModel::TYPE_INCOME,      //收入
                                        'category'   => CashbookModel::CATEGORY_1,       //营业收入
                                        'source'     => CashbookModel::SOURCE_SYSTEM_ADD,//系统自动同步
                                        'amount'     => $amount,
                                        'createdAt'  => $time,
                                        'orderId'    => '',
                                        'remark'     => $yesterday . ' 营业收入',
                                    ];
                            } elseif ($cashbookModel->amount != $amount) {//营业收入不匹配进行修改
                                CashbookModel::query()->where('id', $cashbookModel->id)->update(['amount' => $amount]);
                            }
                            break;
                        case CashbookBillSyncSwitchModel::TYPE_GOODS://自动同步订货账单
                            //查询一个月前到目前的订货单 防止订货单有退款，删除的情况
                            $getOrderListByShopId = OrmNewOrderRemote::getOrderListByShopId(strtotime(date('Y-m-d', strtotime("-1 month"))), $time, $v->shopId);
                            if (isset($getOrderListByShopId) && $getOrderListByShopId['code'] == 200 && count($getOrderListByShopId['data']['list'])) {
                                $orderIds          = array_column($getOrderListByShopId['data']['list'], 'id');
                                $getInfoByOrderIds = CashbookModel::getInfoByOrderId($v->shopId, $orderIds);//查询这些订单号是否存在
                                if ($getInfoByOrderIds) {
                                    $getInfoByOrderIds = $getInfoByOrderIds->keyBy('orderId')->toArray();
                                }
                                foreach ($getOrderListByShopId['data']['list'] as $order) {
                                    if (($order['status'] == 3 && $order['status_text'] == "已完成") || ($order['status'] == 2 && $order['status_text'] == "进行中")) {//正常订单
                                        if (isset($getInfoByOrderIds[$order['id']])) {
                                            if (abs($getInfoByOrderIds[$order['id']]['amount']) != $order['pay_amount'] * 100) {//订货单金额不匹配 修改金额
                                                CashbookModel::query()->where('id', $getInfoByOrderIds[$order['id']]['id'])->update(['amount' => -$order['pay_amount'] * 100]);
                                            }
                                        } else {//新增记录
                                            $date = date('Y-m-d', strtotime($order['create_time']));
                                            $batchData[] =
                                                [
                                                    'shopId'     => $v->shopId,
                                                    'userId'     => $order['create_uid'] ?? 0,//订货人id
                                                    'recordTime' => strtotime($date),
                                                    'type'       => CashbookModel::TYPE_PAY,         //支出
                                                    'category'   => CashbookModel::CATEGORY_5,       //订货
                                                    'source'     => CashbookModel::SOURCE_SYSTEM_ADD,//系统自动同步
                                                    'amount'     => -$order['pay_amount'] * 100,
                                                    'createdAt'  => $time,
                                                    'orderId'    => $order['id'],
                                                    'remark'     => $date . ' 订货',
                                                ];
                                        }
                                    } elseif (isset($getInfoByOrderIds[$order['id']])) {//退款订单 根据单号查询 并删除记录
                                        CashbookModel::query()->where('id', $getInfoByOrderIds[$order['id']]['id'])->update(['isDeleted' => 1]);
                                    }
                                }
                            }
                            break;
                        default:
                            return;
                    }
                }
                if ($batchData) {
                    CashbookModel::batchInsertData($batchData);
                }
            }
            );
    }

}
